import urllib
from urllib.parse import urlparse
from urllib.parse import parse_qs
import json
from cgi import parse_header,parse_multipart
from http.server import BaseHTTPRequestHandler, HTTPServer


class MyRequestHandler(BaseHTTPRequestHandler):

    def parse_POST(self):
        ctype, pdict = parse_header(self.headers['content-type'])
        if ctype == 'application/json':
            length = int(self.headers['content-length'])
            post_values = json.loads(self.rfile.read(length))
            # self.TODOS.append(post_values)
        elif ctype == 'multipart/form-data':
            postvars = parse_multipart(self.rfile, pdict)
        elif ctype == 'application/x-www-form-urlencoded':
            length = int(self.headers['content-length'])
            postvars = parse_qs(
                self.rfile.read(length),
                keep_blank_values=1)
        else:
            postvars = {}
        return postvars

    def do_Handler(self, paramdic:dict):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.send_header("test", "This is test!")
        self.end_headers()
        self.wfile.write(json.dumps(paramdic).encode('UTF-8'))



    def do_GET(self):

        url= str(self.path)
        querydic={}
        if "?" in url:
            querypath = urllib.parse.parse_qs(urllib.parse.unquote(url.split('?', 1)[1]))
            for key in querypath.keys():
                querydic.setdefault(key,querypath[key][0])
        self.do_Handler(querydic)


    def do_POST(self):
         self.do_Handler(self.do_POST())


    '''  else:
        self.send_error(415, "Only json data is supported.")
        return

    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.end_headers()

    self.wfile.write(post_values)'''



if __name__== '__main__':
    server = HTTPServer(('', 8000), MyRequestHandler)
    server.serve_forever()



